<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-form-item label="考试名称">
                        <el-input v-model="searchForm.examName" placeholder="考试名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="15">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="initTableData(1)">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>


        <!-- 新增|刷新 -->
        <div class="flex items-center justify-between mb-4">
            <div>
                <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
            </div>

            <el-tooltip effect="dark" content="刷新数据" placement="top">
                <el-button text @click="initTableData">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-tooltip>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

            <el-table-column label="考试名称" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.examName }}
                </template>
            </el-table-column>

            <el-table-column label="适用人群" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.userRole==1?"工程师":"船员" }}
                </template>
            </el-table-column>

            <!-- <el-table-column label="考试描述" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.examDescription }}
                </template>
            </el-table-column> -->

            <el-table-column label="考试费用（分）" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.money }}
                </template>
            </el-table-column>

            <el-table-column label="考试图片" align="center">
                <template #default="{ row }">
                    <el-image style="width: 60px; height: 60px" :preview-teleported="true" class="images"
                        :hide-on-click-modal=true :src="row.picture" :zoom-rate="1.2" :preview-src-list="[row.picture]"
                        :initial-index="1" fit="cover">
                    </el-image>
                </template>
            </el-table-column>

            <el-table-column label="考试时间限制" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.timeLimit }}
                </template>
            </el-table-column>

            <el-table-column label="单选题个数" align="center">
                <template #default="{ row }">
                    {{ row.oneChoiceNum }}
                </template>
            </el-table-column>

            <el-table-column label="每个单选题分数" align="center">
                <template #default="{ row }">
                    {{ row.oneChoiceScore }}
                </template>
            </el-table-column>

            <el-table-column label="多选题个数" align="center">
                <template #default="{ row }">
                    {{ row.multipleChoiceNum }}
                </template>
            </el-table-column>

            <el-table-column label="每个多选题分数" align="center">
                <template #default="{ row }">
                    {{ row.multipleChoiceScore }}
                </template>
            </el-table-column>

            <el-table-column label="满分" align="center">
                <template #default="{ row }">
                    {{ row.totalScore }}
                </template>
            </el-table-column>

            <el-table-column label="及格分数" align="center">
                <template #default="{ row }">
                    {{ row.passScore }}
                </template>
            </el-table-column>

            <!-- <el-table-column label="对应证书" align="center">
                <template #default="{ row }">
                    {{ row.cert }}
                </template>
            </el-table-column> -->

            <!-- <el-table-column label="创建时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column> -->

            <el-table-column label="操作" width="320" align="center">
                <template #default="scope">
                    <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
                    <div v-else>
                        <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>
                        <!-- <el-button type="primary" size="small" text @click="handleAddPaper(scope.row)">试卷</el-button> -->
                        <el-button type="primary" size="small" text @click="handleAddQuestion(scope.row)">题库</el-button>
                        <el-popconfirm title="是否要删除该考试模版？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="handleDelete(scope.row.configId)">
                            <template #reference>
                                <el-button text type="primary" size="small"
                                    :disabled="scope.row.state == '1'">删除</el-button>
                            </template>
                        </el-popconfirm>
                        <el-button type="primary" size="small" text @click="generateQRCode(scope.row)">二维码</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="initTableData" />
        </div>

        <!-- 新增|修改弹窗 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">
                <el-form-item label="考试类别" prop="categoryId">
                    <el-tree-select v-model="form.categoryId" :data="categoryData" :props="{
                        label: 'name',
                        value: 'id',
                        children: 'children',
                    }" placeholder="课程类别">
                    </el-tree-select>
                </el-form-item>

                <!-- 用户身份，1工程师，2船员 -->
                <el-form-item label="适用人群" prop="userRole">
                    <el-radio-group v-model="form.userRole">
                        <el-radio value="1">工程师</el-radio>
                        <el-radio value="2">船员</el-radio>
                    </el-radio-group> 
                </el-form-item>

                <el-form-item label="考试名称" prop="examName">
                    <el-input v-model="form.examName" placeholder="考试名称"></el-input>
                </el-form-item>

                <el-form-item label="考试描述" prop="examDescription">
                    <el-input v-model="form.examDescription" placeholder="考试描述" type="textarea" :rows="3"></el-input>
                </el-form-item>

                <el-form-item label="考试图片" prop="files">
                    <el-upload class="upload-demo" :class="hideUpload ? 'hide' : ''" list-type="picture-card"
                        ref="upload" accept=".jpg,.png" action="" :limit="1" :on-change="fileChange"
                        :file-list="form.files" :before-upload="beforeUpload" :on-exceed="handleExceed"
                        :on-remove="handleRemove" :http-request="uploadSubmit" :auto-upload="false">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <!-- <el-form-item label="对应证书" prop="cert">
                    <el-select v-model="form.cert" placeholder="对应证书">
                        <el-option v-for="item in certNameList" :key="item.id" :label="item.name" :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item> -->

                <el-form-item label="考试费用" prop="money">
                    <el-input-number v-model="form.money" placeholder="考试费用" :min=1></el-input-number>&nbsp;分
                </el-form-item>

                <el-form-item label="考试时间限制" prop="timeLimit">
                    <el-input-number v-model="form.timeLimit" placeholder="考试时间" :min=1></el-input-number>&nbsp;分钟
                </el-form-item>

                <el-form-item label="单选数量" prop="oneChoiceNum">
                    <el-input-number v-model="form.oneChoiceNum" @change="sumTotalScore" placeholder="单选数量"
                        :min=0></el-input-number>&nbsp;题
                </el-form-item>

                <el-form-item label="每个单选分数" prop="oneChoiceScore">
                    <el-input-number v-model="form.oneChoiceScore" @change="sumTotalScore" placeholder="每个单选分数"
                        :min=1></el-input-number>&nbsp;分
                </el-form-item>

                <el-form-item label="多选数量" prop="multipleChoiceNum">
                    <el-input-number v-model="form.multipleChoiceNum" @change="sumTotalScore" placeholder="多选数量"
                        :min=0></el-input-number>&nbsp;题
                </el-form-item>

                <el-form-item label="每个多选分数" prop="multipleChoiceScore">
                    <el-input-number v-model="form.multipleChoiceScore" @change="sumTotalScore" placeholder="每个多选分数"
                        :min=1></el-input-number>&nbsp;分
                </el-form-item>

                <el-form-item label="考试满分" prop="totalScore">
                    <el-input-number disabled="true" v-model="form.totalScore" placeholder="考试满分"
                        :min=0></el-input-number>&nbsp;分
                </el-form-item>

                <el-form-item label="及格分数" prop="passScore">
                    <el-input-number v-model="form.passScore" placeholder="及格分数" :min=1></el-input-number>&nbsp;分
                </el-form-item>

                <el-form-item label="考试关联课程" prop="preCourse">
                    <el-button plain @click="dialogTableVisible_course = true">
                        {{ null == selectCourseName ? '未选择' : selectCourseName }}
                    </el-button>
                </el-form-item>
            </el-form>
        </FormDrawer>
    </el-card>

    <!-- 选择课程dialog -->
    <SystemDialog title="选择课程" :visible="dialogTableVisible_course" :height="50" :width="70" :showCloseBtn="true"
        :showOkBtn="true" @on-close="dialogTableVisible_course = false" @on-confirm="dialogTableVisible_course = false" okBtnName="选择课程">
        <template v-slot:content>
            <SelectCourse v-if="dialogTableVisible_course" :showSelection="true" :officialCourseList="selectCourseList"
                @getCheckedCourseList="getCheckedCourseList" />
        </template>
    </SystemDialog>

    <SystemDialog title="考试二维码" :visible="showDialog_qrCodeImage" :height="30" :width="25" :showCloseBtn="true"
        :showOkBtn="true" @on-close="showDialog_qrCodeImage = false" @on-confirm="downloadQRCode" okBtnName="下载二维码">
        <template v-slot:content>
            <div class="flex flex-row justify-center align-center">
                <img :src="qrCodeImage" alt="二维码" />
            </div>

        </template>
    </SystemDialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue"
import { toast, toastWarn } from "~/composables/util"
import SystemDialog from "~/components/SystemDialog.vue";
import SelectCourse from "~/components/select-course.vue"
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { api_category_tree } from "~/api/exam/categoryApi"
import { api_examConfig_list, api_examConfig_add, api_examConfig_update, api_examConfig_delete } from "~/api/exam/examPaper"
import { api_cert_list } from "~/api/exam/certApi";
import QRCode from 'qrcode';

//store存储
const store = useStore()

// 全局路由
const router = useRouter()

// 课程类别树形
const categoryData = ref(null)

const certNameList = ref(null)

// 表格分页数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
// 用于存储二维码图片的 Base64 数据
const qrCodeImage = ref(null);
const showDialog_qrCodeImage = ref(false);


// 查询条件
const searchForm = reactive({
    examName: null,
    page: currentPage.value,
    size: limit.value,
})
// 重置搜索框
const resetSearchForm = () => {
    searchForm.examName = null
    initTableData(1)
}

// 生命周期函数
onMounted(() => {

    //获取树形结构字典数据
    initCategoryData()

    //初始化列表数据
    initTableData()

    //初始化证书名称list
    initCertNameList()
})

// 生成二维码
const generateQRCode = (examObj) => {
    console.log('examObj: ', examObj)
    // 获取当前页面的 URL
    const url = `${window.location.protocol}//${window.location.hostname}/exam/#/online/examStart-phone?id=${examObj.configId}&code=${Date.now()}`;
    console.log('exam url: ', url)

    // 生成二维码并转换为 Base64 图片
    QRCode.toDataURL(url, { width: 200, margin: 2 }, (err, url) => {
        if (err) {
            console.error('生成二维码失败:', err);
            return;
        }
        qrCodeImage.value = url;
        showDialog_qrCodeImage.value = true
    });
};

// 下载二维码
const downloadQRCode = () => {
    const link = document.createElement('a');
    link.href = qrCodeImage.value;
    link.download = 'qrcode.png';
    link.click();
    showDialog_qrCodeImage.value = false;
};

// 获取数据
function initCategoryData() {
    api_category_tree().then(res => {
        categoryData.value = res
    })
}


// 初始化证书名称list
function initCertNameList() {
    let paramIo = {}
    paramIo.state = 1
    paramIo.size = 1000
    api_cert_list(paramIo).then(res => {
        if (res && res.records) {
            certNameList.value = res.records
        } else {
            certNameList.value = null
        }
    })
}

// 表单部分
// 是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
    categoryId: null,
    // 用户身份，1工程师，2船员
    userRole: "1",
    examName: null,
    examDescription: null,
    preCourse: null,
    cert: null,
    timeLimit: null,
    oneChoiceNum: null,
    oneChoiceScore: null,
    multipleChoiceNum: null,
    multipleChoiceScore: null,
    totalScore: null,
    passScore: null,
    money: null,
    files: []
})

//执行表单校验
const rules = {
    categoryId: [
        { required: true, message: '考试类别不能为空', trigger: 'change' }
    ],
    userRole: [
        { required: true, message: '适用人群不能为空', trigger: 'change' }
    ],
    examName: [
        { required: true, message: '考试名称不能为空', trigger: 'change' }
    ],
    examDescription: [
        { required: true, message: '考试描述不能为空', trigger: 'change' }
    ],
    preCourse: [
        { required: true, message: '考试前置课程不能为空', trigger: 'change' }
    ],
    // cert: [
    //     { required: true, message: '考试对应证书不能为空', trigger: 'change' }
    // ],
    timeLimit: [
        { required: true, message: '考试时间限制不能为空', trigger: 'change' }
    ],
    oneChoiceNum: [
        { required: true, message: '单选题个数不能为空', trigger: 'change' }
    ],
    oneChoiceScore: [
        { required: true, message: '每个单选题分数不能为空', trigger: 'change' }
    ],
    multipleChoiceNum: [
        { required: true, message: '多选题个数不能为空', trigger: 'change' }
    ],
    multipleChoiceScore: [
        { required: true, message: '每个多选题分数不能为空', trigger: 'change' }
    ],
    totalScore: [
        { required: true, message: '考试总分不能为空', trigger: 'change' }
    ],
    passScore: [
        { required: true, message: '考试及格分不能为空', trigger: 'change' }
    ],
    files: [
        { required: true, message: '考试图片不能为空', trigger: 'change' }
    ],
    money: [
        { required: true, message: '考试费用不能为空', trigger: 'change' }
    ],
}


// 选择课程
const dialogTableVisible_course = ref(false)
const selectCourseList = ref(null)
const selectCourseName = ref(null)

// 获取选择的课程
function getCheckedCourseList(checkedDataList) {
    //console.log(JSON.stringify(checkedDataList))
    if (null != checkedDataList && checkedDataList.length > 0) {
        let ids = []
        let names = ""
        for (let o of checkedDataList) {
            ids.push(o.id)
            names += o.title + ","
        }
        form.preCourse = ids
        selectCourseName.value = names.substring(0, names.length - 1)
        formRef.value.clearValidate(['preCourse'])
    } else {
        form.preCourse = null
        selectCourseName.value = null
    }
}

//提交表单
const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return

        //分数逻辑校验
        if (form.totalScore <= 0) {
            toastWarn("总分数必须大于0")
            return
        }
        if (form.passScore > form.totalScore) {
            toastWarn("及格分数不能大于总分数")
            return
        }

        //新增
        if (editId.value == 0) {
            //触发文件上传
            upload.value.submit();
        }
        else {
            if (editImgChanged.value == true) {
                //触发文件上传
                upload.value.submit();
            }
            else {
                let paramIo = new FormData()// FormData 对象
                paramIo.append('configId', editId.value)
                paramIo.append('categoryId', form.categoryId)
                paramIo.append('userRole', form.userRole)
                paramIo.append('examName', form.examName)
                paramIo.append('examDescription', form.examDescription)
                paramIo.append('preCourse', form.preCourse)
                paramIo.append('cert', form.cert)
                paramIo.append('timeLimit', form.timeLimit)
                paramIo.append('oneChoiceNum', form.oneChoiceNum)
                paramIo.append('oneChoiceScore', form.oneChoiceScore)
                paramIo.append('multipleChoiceNum', form.multipleChoiceNum)
                paramIo.append('multipleChoiceScore', form.multipleChoiceScore)
                paramIo.append('totalScore', form.totalScore)
                paramIo.append('passScore', form.passScore)
                paramIo.append('money', form.money)
                //loading
                formDrawerRef.value.showLoading()
                const fun = api_examConfig_update(paramIo)
                fun.then(res => {
                    toast(drawerTitle.value + "成功")
                    //清空file文件
                    upload.value.clearFiles();
                    //修改刷新当前页，新增刷新第一页
                    initTableData(editId.value ? false : 1)
                    formDrawerRef.value.close()
                })
                    .finally(() => {
                        //close loading
                        formDrawerRef.value.hideLoading()
                    })
            }
        }
    })
}

// 新增按钮点击事件
const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    hideUpload.value = false
    resetForm({
        categoryId: null,
        // 用户身份，1工程师，2船员
        userRole: "1",
        examName: null,
        examDescription: null,
        preCourse: null,
        cert: null,
        timeLimit: null,
        oneChoiceNum: null,
        oneChoiceScore: null,
        multipleChoiceNum: null,
        multipleChoiceScore: null,
        totalScore: null,
        passScore: null,
        money: null,
        files: []
    })
    //清空证书关联课程
    selectCourseList.value = null
    selectCourseName.value = null
    //打开弹窗
    formDrawerRef.value.open()
}

// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 上传组件 -------------------------------------------
//上传组件
const upload = ref(null)
const hideUpload = ref(false)
const editImgChanged = ref(false)
// 文件改变
const fileChange = (file, fileList) => {
    form.files = fileList;
    hideUpload.value = true
    editImgChanged.value = true
    // console.log(JSON.stringify(form.files))
}
// 文件超出个数限制
const handleExceed = (file, fileList) => {
    toastWarn('只能选择一个文件');
}
// 文件移除
const handleRemove = (file, fileList) => {
    form.files = [];
    hideUpload.value = false
}
// 上传前 文件校验
const beforeUpload = (file) => {
    //console.log("==============" + JSON.stringify(file))
    const isLt2M = file.size / 1024 / 1024 < 10
    if (!isLt2M) {
        toastWarn('上传文件大小不能超过 10MB!')
        return false;
    }
    return true;
}
//提交上的文件
const uploadSubmit = (param) => {
    let fileObj = param.file// 相当于input里取得的files
    let paramIo = new FormData()// FormData 对象
    paramIo.append('configId', editId.value)
    paramIo.append('files', fileObj)// 文件对象
    paramIo.append('categoryId', form.categoryId)
    paramIo.append('userRole', form.userRole)
    paramIo.append('examName', form.examName)
    paramIo.append('examDescription', form.examDescription)
    paramIo.append('preCourse', form.preCourse)
    paramIo.append('cert', form.cert)
    paramIo.append('timeLimit', form.timeLimit)
    paramIo.append('oneChoiceNum', form.oneChoiceNum)
    paramIo.append('oneChoiceScore', form.oneChoiceScore)
    paramIo.append('multipleChoiceNum', form.multipleChoiceNum)
    paramIo.append('multipleChoiceScore', form.multipleChoiceScore)
    paramIo.append('totalScore', form.totalScore)
    paramIo.append('passScore', form.passScore)
    paramIo.append('money', form.money)

    //loading
    formDrawerRef.value.showLoading()
    const fun = editId.value == 0 ? api_examConfig_add(paramIo) : api_examConfig_update(paramIo)
    fun.then(res => {
        toast(drawerTitle.value + "成功")
        //清空file文件
        upload.value.clearFiles();
        //修改刷新当前页，新增刷新第一页
        initTableData(editId.value ? false : 1)
        formDrawerRef.value.close()
    })
        .finally(() => {
            //close loading
            formDrawerRef.value.hideLoading()
        })
}
// 上传组件 -------------------------------------------


// 获取数据
function initTableData(p = null) {
    //指定页码是否为空
    if (typeof p == "number") {
        currentPage.value = p
    }

    loading.value = true
    searchForm.page = currentPage.value

    api_examConfig_list(searchForm)
        .then(res => {
            if (res) {
                tableData.value = res.records
                total.value = Number(res.total)
            } else {
                tableData.value = []
                total.value = 0
            }
        })
        .finally(() => {
            loading.value = false
        })
}

// 编辑
const handleEdit = (row) => {
    editId.value = row.configId
    row.oneChoiceNum = Number(row.oneChoiceNum)
    row.oneChoiceScore = Number(row.oneChoiceScore)
    row.multipleChoiceNum = Number(row.multipleChoiceNum)
    row.multipleChoiceScore = Number(row.multipleChoiceScore)
    row.totalScore = Number(row.totalScore)
    row.passScore = Number(row.passScore)
    resetForm(row)
    //回显图片
    form.files = [{ url: row.picture }]
    hideUpload.value = true
    editImgChanged.value = false
    //回显关联课程，字符串转数组
    form.preCourse = row.preCourse.split(",")

    let ids = row.preCourse.split(",")
    let names = row.preCourseName.split(",")

    selectCourseList.value = []
    for (let i = 0; i < ids.length; i++) {
        selectCourseList.value.push({ "id": ids[i], "title": names[i] })
    }

    selectCourseName.value = row.preCourseName
    formDrawerRef.value.open()
}

// 删除
const handleDelete = (id) => {
    loading.value = true
    api_examConfig_delete(id).then(res => {
        toast("删除成功")
        initTableData()
    })
        .finally(() => {
            loading.value = false
        })
}


// 试卷
const handleAddPaper = (row) => {
    //试卷ID
    store.commit("SetConfigId", row.configId)
    //跳转界面
    router.push({
        path: '/examPaper',
    });
}

// 题目
const handleAddQuestion = (row) => {
    //试卷ID
    store.commit("SetConfigId", row.configId);
    //跳转界面
    router.push({
        path: "/examQuestion",
    });
};

// 计算总分
const sumTotalScore = (value) => {
    let totalScore = form.oneChoiceNum * form.oneChoiceScore + form.multipleChoiceNum * form.multipleChoiceScore
    form.totalScore = totalScore
}

</script>

<style scoped>
.hide ::v-deep .el-upload--picture-card {
    display: none;
}
</style>